<template>
  <div>
    <el-row>
      <el-select v-model="defaultCheckedItems" multiple :disabled="readonly" value-key="userId" class="w-full-select">
        <el-option v-for="item in defaultCheckedItems" :key="item.userId" :label="item.realName" :value="item" />
      </el-select>
      <el-button type="primary" :loading="loading" style="margin-left:10px" :disabled="readonly" @click="onAdd">添加</el-button>
    </el-row>

    <el-dialog class="small-dialog" title="人员列表" :visible.sync="showPerson" append-to-body>
      <div>
        <el-row class="m-b-20">
          <el-select v-model="checkedItems" multiple value-key="userId" class="w-full" @remove-tag="(value) => onDelCheckedItem(value.userId)">
            <el-option
              v-for="item in checkedItems"
              :key="item.userId"
              :label="item.realName"
              :value="item"
              :disabled="readonly"
              @click.native="onDelCheckedItem(item.userId)"
            />
          </el-select>
        </el-row>
        <el-tabs v-model="schoolTab" type="border-card">
          <el-tab-pane
            v-for="item in allData"
            :key="item.schoolId"
            :label="item.schoolName"
            :name="item.schoolId"
          >
            <el-tabs v-model="item.userTab">
              <el-tab-pane v-if="needAgency" label="按字母" name="1" />
              <el-tab-pane v-if="needAgency" label="按机构" name="2" />

              <user-list
                v-show="item.userTab === '1'"
                :data="item.sysUserDtoList"
                :disabled="disabled"
                :disabled-all="disabledAll"
                @checked-all="onCheckedAll"
                @change="onChange"
              />
              <user-list
                v-if="item.userTab === '2'"
                :data="item.agencyUserDtoList"
                :disabled="disabled"
                :disabled-all="disabledAll"
                @checked-all="onCheckedAll"
                @change="onChange"
              />
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancelPerson"> 取消 </el-button>
        <el-button type="primary" :disabled="!checkedItems.length" @click="onConfirmPerson">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserList from './UserList'
export default {
  components: {
    UserList
  },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    schoolId: {
      type: String,
      default: ''
    },
    readonly: { // 是否只读
      type: Boolean,
      default: false
    },
    needAgency: { // 是否展示机构TAB
      type: Boolean,
      default: true
    },
    multipleLimit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      loading: false,
      showPerson: false,
      schoolTab: '',
      allData: [],
      defaultCheckedItems: [], // 默认选中的Items
      checkedItems: [] // 弹框中选中的Items
    }
  },
  computed: {
    disabledAll() {
      return this.multipleLimit !== 0
    },
    disabled() {
      return this.multipleLimit !== 0 && this.checkedItems.length >= this.multipleLimit
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.defaultCheckedItems = val
      }
    },
    defaultCheckedItems: {
      deep: true,
      handler(val) {
        this.$emit('input', val)
      }
    }
  },
  methods: {
    async onAdd() {
      await this.initData()
      if (this.defaultCheckedItems.length) {
        this.allData.forEach(item => {
          this.defaultCheckedItems.forEach(checkedItem => {
            if (checkedItem.schoolId === item.schoolId) {
              let ids = this.defaultCheckedItems.map(item => {
                if (checkedItem.schoolId === item.schoolId) {
                  return checkedItem.userId
                }
              })
              item.sysUserDtoList = this.handleCheckedData(true, ids, item.sysUserDtoList)
              if (this.needAgency) {
                item.agencyUserDtoList = this.handleCheckedData(true, ids, item.agencyUserDtoList)
              }
            }
          })
        })
        this.getCheckedItems()
      }
      this.showPerson = true
    },
    async initData() {
      this.loading = false
      const params = {
        schoolId: this.schoolId && this.schoolId === '' ? '' : this.schoolId,
        isNeedAgency: this.needAgency ? '1' : '0'
      }
      await this.$api.getTeacherList(params).then(({ data }) => {
        this.loading = false
        this.schoolTab = data[0].schoolId
        data.forEach(item => {
          this.$set(item, 'userTab', '1')
          item.sysUserDtoList = this.handleInitData(item.sysUserDtoList, item.schoolId)
          if (this.needAgency) {
            item.agencyUserDtoList = this.handleInitData(item.agencyUserDtoList, item.schoolId)
          }
        })
        this.allData = data
      }).catch(() => {
        this.loading = false
      })
    },
    handleInitData(data, schoolId) {
      if (data && data.length) {
        data.forEach(item => {
          this.$set(item, 'checkAll', false)
          this.$set(item, 'checkedItemIds', [])
          if (item.childrenList && item.childrenList.length) {
            item.childrenList.forEach(userItem => {
              this.$set(userItem, 'schoolId', schoolId)
            })
          }
        })
      }
      return data || []
    },
    onConfirmPerson() {
      if (!this.checkedItems.length) {
        this.$message.warning('至少选择一项')
        return
      }
      this.defaultCheckedItems = this.$deepClone(this.checkedItems)
      this.checkedItems = []
      this.showPerson = false
    },
    onCancelPerson() {
      this.showPerson = false
    },
    /**
     * @description:
     * @param {*} userId
     * @param {String} delType  删除方式(default-默认删除，modal-弹窗删除)
     * @return {*}
     */
    onDelCheckedItem(userId) {
      this.handleChangeAllData(false, [userId])
    },
    /**
     * @description: 全选
     * @param {*} checkedAll
     * @param {*} checkedItemIds
     * @return {*}
     */
    onCheckedAll({ checkedAll, checkedItemIds }) {
      this.handleChangeAllData(checkedAll, checkedItemIds)
    },
    /**
     * @description: 单选
     * @param {*} checked
     * @param {*} userId
     * @return {*}
     */
    onChange({ checked, userId }) {
      this.handleChangeAllData(checked, [userId])
    },
    handleChangeAllData(checked, ids) {
      this.allData.forEach(item => {
        if (item.schoolId === this.schoolTab) {
          item.sysUserDtoList = this.handleCheckedData(checked, ids, item.sysUserDtoList)
          item.agencyUserDtoList = this.handleCheckedData(checked, ids, item.agencyUserDtoList)
        } else {
          if (checked) {
            item.sysUserDtoList = this.handleCheckedData(false, ids, item.sysUserDtoList)
            item.agencyUserDtoList = this.handleCheckedData(false, ids, item.agencyUserDtoList)
          }
        }
      })
      this.getCheckedItems()
    },
    handleCheckedData(checked, ids, data) {
      if (data && data.length) {
        data.forEach(subItem => {
          if (checked) {
            subItem.childrenList.forEach(userItem => {
              if (ids.includes(userItem.userId)) {
                subItem.checkedItemIds.push(userItem.userId)
                subItem.checkedItemIds = Array.from(new Set(subItem.checkedItemIds))
              }
            })
          } else {
            subItem.childrenList.forEach(userItem => {
              if (ids.includes(userItem.userId)) {
                let list = subItem.checkedItemIds.filter(checkedId => userItem.userId !== checkedId)
                subItem.checkedItemIds = list
              }
            })
          }
          subItem.checkAll = this.getCheckAllStatus(subItem)
        })
      }

      return data
    },

    getCheckAllStatus(item) {
      return item.checkedItemIds.length === item.childrenList.length
    },
    /**
     * @description: 获取已选项
     * @param {*}
     * @return {*}
     */
    getCheckedItems() {
      let list = []
      let temp = {}
      this.allData.forEach(item => {
        item.sysUserDtoList.forEach(subItem => {
          if (subItem.checkedItemIds.length) {
            subItem.childrenList.forEach(userItem => {
              if (subItem.checkedItemIds.includes(userItem.userId)) {
                if (!temp[userItem.userId]) {
                  list.push(userItem)
                }
                temp[userItem.userId] = userItem
              }
            })
          }
        })
        if (this.needAgency) {
          item.agencyUserDtoList.forEach(subItem => {
            if (subItem.checkedItemIds.length) {
              subItem.childrenList.forEach(userItem => {
                if (subItem.checkedItemIds.includes(userItem.userId)) {
                  if (!temp[userItem.userId]) {
                    list.push(userItem)
                  }
                  temp[userItem.userId] = userItem
                }
              })
            }
          })
        }
      })
      this.checkedItems = list
    }
  }
}
</script>

